package com.csl.jsonpreference.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.csl.jsonpreference.R
import com.csl.jsonpreference.bean.ConfigTYPE
import com.csl.jsonpreference.configdes.JsonArrayPreference
import com.csl.jsonpreference.configdes.JsonBasePreference
import com.csl.jsonpreference.configdes.JsonConfigIns
import com.csl.jsonpreference.configdes.JsonObjectPreference
import com.csl.jsonpreference.databinding.FragmentJsonpreferenceBinding
import com.csl.jsonpreference.util.CLog
import com.csl.ui.utils.colorpicker.ColorPickerDialog
import com.google.gson.Gson
import com.google.gson.JsonObject
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.json.JSONObject

class JsonPreferenceFragment : Fragment() {



    var viewBinding: FragmentJsonpreferenceBinding? = null
    var configData: JsonObjectPreference? = null
        set(value) {
            field = value
            lifecycleScope.launchWhenResumed {
                adapter.resetData(configData!!.jsonData, value?.getParamsList())
                CLog.d("刷新配置布局: $value")
                adapter.notifyDataSetChanged()
            }
        }

    var adapter = object : JsonPreferenceAdapter() {
        override fun onPreferenceClick(index: Int, data: JSONObject, config: JsonConfigIns) {
            CLog.d("json", "index($index), data:($data), config:($config)")
            when (config.configType) {
                ConfigTYPE.BOOLEAN -> {
                    var bData = data.optBoolean(config.key, false)
                    data.put(config.key, !bData)
                    notifyItemChanged(index)
                }
                ConfigTYPE.ENUM -> {
                    if(config is JsonBasePreference) {
                        config.getEnumType()
                        val arrays = config.getEnumType()!!
                        ListChoseDialog<Enum<*>>(
                            title = config.title,
                            content = config.describe,
                            *arrays
                        ) {
                            CLog.d("enum", "选择新枚举:${it} : ${Gson().toJson(it)}")
                            //使用Gson做中转取值
                            var jsonValue = JSONObject()
                            jsonValue.put("value", it)
//                            data.put(config.key, jsonValue.getString("value"))
                            var trueValue = Gson().toJson(it).replace("\"", "")
                            CLog.d("enum", "设置枚举值:${config.key}:${trueValue}")
                            data.put(config.key, Gson().toJson(it).replace("\"", ""))
                            notifyItemChanged(index)
                        }.show(parentFragmentManager, "enumconfig")

                    }
                }

                ConfigTYPE.OBJECT -> {
                    var groupConfig = config as JsonObjectPreference
                    onOpenOrCloseListener?.onGroupOpen(groupConfig)
                }

                ConfigTYPE.COLOR -> {
                    var colorDialog = ColorPickerDialog(
                        context,
                        data.optInt(
                            config.key,
                            requireActivity().resources.getColor(R.color.colorPrimary)
                        )
                    )
                    colorDialog.setOnColorChangedListener {
                        data.put(config.key, it)
                        notifyItemChanged(index)
                    }
                    colorDialog.show()
                }

//                ConfigTYPE.ARRAY_BOOLEAN,
//                ConfigTYPE.ARRAY_FLOAT,
//                ConfigTYPE.ARRAY_NUMBER,
//                ConfigTYPE.ARRAY_TXT,
                ConfigTYPE.ARRAY_OBJECT -> {
                    var groupConfig = config as JsonArrayPreference
                    onOpenOrCloseListener?.onArrayOpen(groupConfig)
//                    showToast("数组类型: ${config.configType}")
                }
//                is EnumPreference -> {
//                    var enumDialog = ListChoseDialog<Enum<*>>(
//                        config.discribe, "",
//                        *config.alltype
//                    ) { it ->
//                        config.value = it
//                        notifyDataSetChanged()
//                        true
//                    }
//                    enumDialog.show(parentFragmentManager, "enumconfig")
//                }

                else -> {
                    TxtPreferenceDialog(
                        config.title,
                        config.describe,
                        data.optString(config.key, ""),
                        if(!config.values.isNullOrEmpty()) {
                            ArrayList<String>().apply {
                                addAll(config.values!!)
                            }
                        } else {
                            null
                        }
                    ) {
                        when (config.configType) {
                            ConfigTYPE.FLOAT -> {
                                it.toFloatOrNull()?.let {
                                    data.put(config.key, it)
                                    notifyItemChanged(index)
                                } ?: let {
                                    showToast("输入错误, 非浮点数")
                                }
                            }

                            ConfigTYPE.NUMBER -> {
                                it.toIntOrNull()?.let {
                                    data.put(config.key, it)
                                    notifyDataSetChanged()
                                } ?: let {
                                    showToast("输入错误, 非数字")
                                }
                            }

                            else -> {
                                data.put(config.key, "$it")
                            }
                        }
                        notifyItemChanged(index)
                    }.show(parentFragmentManager, "txtconfig")
                }

            }

        }
    }

    var onOpenOrCloseListener: OnOpenOrCloseListener? = null


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        viewBinding = FragmentJsonpreferenceBinding.inflate(inflater)

        return viewBinding!!.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)



        viewBinding!!.rvConfig.layoutManager = LinearLayoutManager(context);
        viewBinding!!.rvConfig.adapter = adapter
//        adapter.datas = root.value
//        adapter.notifyDataSetChanged()
    }


    override fun onDestroyView() {
        super.onDestroyView()
        viewBinding = null
    }

    fun showToast(str: String) {
        lifecycleScope.launchWhenCreated {
            withContext(Dispatchers.Main) {
                Toast.makeText(context, "$str", Toast.LENGTH_SHORT).show()
            }
        }
    }

    override fun onResume() {
        CLog.d("life", "json resume")
        super.onResume()
    }
}